<script setup>
import { validateEmailService,startResetService,doResetService } from '@/api/user/user'
import { useMessage} from 'naive-ui'
import { ref } from 'vue'
import md5 from 'js-md5'
import {useRouter} from "vue-router"
const router = useRouter()
// 登录表单
const loginForm = ref({
  Email: "",
  code: "",
  password:"",
  password_repeat:""
})
const message=useMessage()
let flag =ref(0)
let passwordValid1 = false
let passwordValid2 = false
let passwordMismatch = false

const validatePassword = () => {
  //console.log('Validating password...')
  flag=1
  const regex1 = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&.#])[A-Za-z\d@$!%*?&.#]+$/
  const regex2 = /^.{6,8}$/
  passwordValid1 = regex1.test(loginForm.value.password)
  passwordValid2 = regex2.test(loginForm.value.password)
  //console.log(loginForm.value.password)
}

const checkPasswordMatch = () => {
  console.log('Checking password match...')
  passwordMismatch = loginForm.value.password_repeat !== loginForm.value.password
}
const formRef=ref()
const coldTime=ref(0)
let flag2 =ref(0)
let emailValid = false
const EmailValidate = () => {
  console.log('Validating email...')
  flag2=1
  const regexEmail = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$/
  emailValid = regexEmail.test(loginForm.value.Email)
  console.log(loginForm.value.Email)
}

const validateEmail=async()=>{
  //event.preventDefault()
  console.log(loginForm.value.Email);
  const {data:res}=await validateEmailService(loginForm.value.Email)
  if(res.code==1)
  { sessionId.value=res.data
    message.success("邮件已发送，请注意查收！")
    console.log(res);
  }
  if (res.code==0)
  {
    message.error("用户邮箱不存在")
    router.push('/login')
  }
  // alert(res.data)
  coldTime.value =60
  setInterval(()=>coldTime.value--,1000)//每秒钟冷却时间减一，在发送邮件后的一分钟内不能再次请求发送验证码

}
const sessionId=ref('')
const startReset = async () => {
  //event.preventDefault()
  //formRef.value.validate(async () => {
  const { data: res } = await startResetService(loginForm.value.Email, loginForm.value.code,sessionId.value)
  active.value++
  //alert(res.data)
  // Process the response here

  //})
}

const doReset = async () => {
  console.log("立即重置");
  //阻止默认表单提交
  //event.preventDefault()
  const encryptedPassword = md5(loginForm.value.password);
  // 将加密后的密码设置回表单对象
  loginForm.value.password = encryptedPassword;
  const { data: res } = await doResetService(loginForm.value.Email,loginForm.value.password)
  // alert(res.data)
  router.push('/')


}
const active=ref(0)
function logAndNavigate() {
  console.log('忘记密码');
  router.push('/login');
}
</script>

<template>

  <div class="container"  v-if="active===0">
    <div class="loginForm">
      <div class="title">重置密码</div>

      <form  ref="formRef">
        <label for="username">邮箱</label>
        <n-input type="text" placeholder="请输入学校邮箱" id="useremail" v-model:value="loginForm.Email"  @input="EmailValidate"></n-input>
        <div v-if="!emailValid&&flag2" style="color: red; margin-top: 5px;" >
          请输入合法的邮件地址
        </div>
        <label for="password">验证码</label>
        <div class="code-container" style="display: flex; align-items: center;">
          <n-input type="text" placeholder="请输入验证码" id="code" v-model:value="loginForm.code" style="width:300px;vertical-align:top;padding:0;    margin:0;" ></n-input>
          <n-button @click="validateEmail" :disabled="!emailValid.valueOf || coldTime .valueOf>0" style="width: 150px;vertical-align:top;padding:0;    margin:0;margin-left: 80px;">
            {{ coldTime>0 ? '请稍后'+coldTime+'秒':'获取验证码' }}
          </n-button>
        </div>
        <div class="flex-container text-right">
          <n-a class="alink" @click.prevent="logAndNavigate">已有密码？返回登陆界面</n-a>
        </div>
        <n-button @click="startReset()">开始重置密码</n-button>
      </form>
    </div>
  </div>
  <div class="container" v-if="active === 1">
    <div class="loginForm" style="width: 450px;min-height: 400px;background-color:white;border-radius: 5px;">
      <div class="title">重置密码</div>
      <form  ref="formRef">
        <label for="password" >新密码</label>
        <n-input type="password" placeholder="请输入新密码" id="userpassword" v-model:value="loginForm.password"  @input="validatePassword"></n-input>
        <div v-if="flag" style="color: red; margin-top: 5px;">
          <div v-if="!passwordValid1&&passwordValid2">
            密码必须包含大、小写字母、数字和特殊字符@$!%*?&.#
          </div>
          <div v-if="passwordValid1&&!passwordValid2">
            密码长度6-18位
          </div>
          <div v-if="!passwordValid1&&!passwordValid2">
            密码必须包含大、小写字母、数字和特殊字符
            密码长度6-18位
          </div>

        </div>
        <label for="password_repeat">重复密码</label>
        <n-input type="password" placeholder="请再次输入新密码" id="password_repeat" v-model:value="loginForm.password_repeat" prop="password_repeat" @input="checkPasswordMatch"></n-input>
        <div v-if="passwordMismatch" style="color: red;margin-top: 5px;">两次密码不一致</div>
        <div class="alink" @click.prevent="logAndNavigate" style="margin-top: 20px;float: left">已有密码？返回登陆界面</div>
        <n-button :disabled="passwordMismatch" @click="doReset()">重置密码</n-button>

      </form>
    </div>
  </div>


</template>

<style scoped>
.container{
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url('@/assets/login.webp');
  background-size: cover;
}
.loginForm{
  width: 450px;
  min-height: 400px;
  background-color:white;
  border-radius: 5px;
}
.title{
  margin-top: 5px;
  text-align: center;
  font-size: 35px;
}
form{
  width: auto;
  padding: 0 30px;
  box-sizing:border-box;
}
label {
  display: block;
  margin-top: 30px;
  font-size: 16px;
}
input {
  display: block;
  height: 45px;
  width: 100%;
  border-radius: 5px;
  padding: 0 10px;
  margin-top: 8px;
  font-size: 14px;
  font-weight: 300;
  box-sizing:border-box;
  border: 1px solid rgb(218, 210, 210);
}
button {
  margin-top: 50px;
  width: 100%;
  color: white;
  padding: 10px 0;
  font-size: 18px;
  font-weight: 600;
  border-radius: 10px;
  cursor: pointer;
  background-color: rgb(17, 138, 236);
  border: 0;
}
.flex-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  display: block;
  margin-left: 220px;
}
.alink {
  text-align: right;
  color: inherit;
  transition: all 0.3s;
  text-decoration: none;
  color: grey;
}
.alink:hover{
  /* 当鼠标悬停时 */
  color: #007bff;
  text-decoration: underline;
}

</style>


